package com.huanglejing.shanggou.activity

import android.Manifest
import android.annotation.TargetApi
import android.app.ProgressDialog
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.net.Uri
import android.os.AsyncTask
import android.os.Build
import android.os.Bundle
import android.support.design.widget.TabLayout
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import android.support.v4.content.FileProvider
import android.support.v4.view.ViewPager
import android.util.Log
import android.view.KeyEvent
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.ImageView
import android.widget.Space
import android.widget.TextView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.animation.GlideAnimation
import com.bumptech.glide.request.target.SimpleTarget
import com.huanglejing.mylibrary.KLog
import com.huanglejing.shanggou.R
import com.huanglejing.shanggou.anim.FadeInOutPageTransformer
import com.huanglejing.shanggou.bean.UpdateInfo
import com.huanglejing.shanggou.common.AppBaseActivity
import com.huanglejing.shanggou.data.getTabView
import com.huanglejing.shanggou.data.mTabRes
import com.huanglejing.shanggou.data.mTabResPressed
import com.huanglejing.shanggou.data.setShareBitmap
import com.huanglejing.shanggou.fragment.*
import com.huanglejing.shanggou.interfaces.MainContract.MainPresenter
import com.huanglejing.shanggou.interfaces.MainContract.MainView
import com.huanglejing.shanggou.presenterimpl.MainPresenterImpl
import com.huanglejing.shanggou.rx.SimpleSubscriber
import com.huanglejing.shanggou.rx.event.JumpToCompanyEvent
import com.huanglejing.shanggou.rx.event.JumpToHomeEvent
import com.huanglejing.shanggou.rx.rxbus.RxBus
import com.huanglejing.shanggou.utils.C
import com.huanglejing.shanggou.utils.ToastUtils
import com.huanglejing.shanggou.utils.addTo
import com.huanglejing.shanggou.utils.pinnedToolBar
import com.huanglejing.shanggou.view.ConfirmDialog
import com.tbruyelle.rxpermissions.RxPermissions
import kotlinx.android.synthetic.main.main_head.*
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL

class MainActivity : AppBaseActivity<MainPresenter<MainView>, MainView>(), MainView {
    private var exitTime: Long = 0
    //  val bottomBar: BottomBar?  by lazy { findView<BottomBar>(R.id.main_bottom_bar) }
    val mRightText: TextView?  by lazy { findViewById<TextView>(R.id.tv_login_language) }
    private var mTabLayout: TabLayout? = null
    private val mViewPager: ViewPager? by lazy { findView<ViewPager>(R.id.main_container) }

    private var lastMenuIndex = 0
    private var mSectionsPagerAdapter: SectionsPagerAdapter? = null
    private var currentMenu: Menu? = null
    private var rxPermissions: RxPermissions? = null
    private var progressDialog: ProgressDialog? = null

    private var isApkDone: Boolean = true;

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mTabLayout = findViewById<TabLayout>(R.id.bottom_tab_layout);

        Glide.with(this@MainActivity)
                .load(R.mipmap.ic_launcher)
                .asBitmap()
                .placeholder(R.drawable.ic_img_error)
                .error(R.drawable.ic_img_error)
                .into(object : SimpleTarget<Bitmap>() {
                    override fun onResourceReady(resource: Bitmap?, glideAnimation: GlideAnimation<in Bitmap>?) {
                        setShareBitmap(resource)
                    }
                })
        //  bottomBar?.setOnSystemUiVisibilityChangeListener { }

        RxBus.get().toObservable(JumpToCompanyEvent::class.java)
                .doOnNext {
                    mViewPager?.currentItem = 1
                }.subscribe(SimpleSubscriber()).addTo(rxManager)
        RxBus.get().toObservable(JumpToHomeEvent::class.java)
                .doOnNext {
                    mViewPager?.currentItem = 0
                }.subscribe(SimpleSubscriber()).addTo(rxManager)
        initViews()
        requestPermission()
        initMainAction()//初始化动作

    }

    fun initMainAction() {
        (intent?.extras?.getSerializable(C.BundleKey.KEY1) as? UpdateInfo)?.let {
            showUpdate(it)
        }
    }

    private fun showUpdate(it: UpdateInfo) {
        if (it.needupdate ?: false) {

            val dialog = ConfirmDialog(this@MainActivity, resources.getString(R.string.str_new_version), it.needupdate
                    ?: false, object : ConfirmDialog
            .ClickListenerInterface {
                override fun doConfirm() {
                    progressDialog = ProgressDialog(this@MainActivity);
                    progressDialog?.setTitle(resources.getString(R.string.str_downloading));
                    progressDialog?.setCanceledOnTouchOutside(true);
                    progressDialog?.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                    //  downloadAsyncTask().execute(it?.url ?: "");
                    downloadAsyncTask().execute(it?.url?:""); //"https://cfzxsoft.oss-cn-hangzhou.aliyuncs.com/cfzx.apk"
                }

                override fun doCancel() {
                }
            });

            dialog?.setCancelable(false);
            dialog?.show();
        }
    }


    override fun onResume() {
        super.onResume()
        //    bottomBar?.getTabWithId(R.id.main_tab_contact)?.setBadgeCount(1);
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_DOWN) {
            if (System.currentTimeMillis().minus(exitTime) > 4000) {
                ToastUtils.toastLong(resources.getString(R.string.str_press_exit))
                exitTime = System.currentTimeMillis()
            } else {
                finish()
                //   System.exit(0)
            }
            return true
        }
        return super.onKeyDown(keyCode, event)
    }

    private fun initViews() {
        this.pinnedToolBar()
        setToolBar(R.id.main_toolbar, mToolBarOptions)
        toolBar.title = resources.getString(R.string.app_name)
        toolBar.subtitle = resources.getString(R.string.app_name)
        setAPPTitle(resources.getString(R.string.app_name))
        mSectionsPagerAdapter = SectionsPagerAdapter(supportFragmentManager)
        mViewPager?.setPageTransformer(true, FadeInOutPageTransformer())
        mViewPager?.adapter = this.mSectionsPagerAdapter
        mViewPager?.offscreenPageLimit = 5 //缓存5页
        mViewPager?.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

            }

            override fun onPageSelected(position: Int) {


                invalidateOptionsMenu()//重绘菜单资源
                val spaceView = this@MainActivity.toolbarLayout?.getChildAt(0) as? Space
                if ((position == 1 || position == 4) && spaceView != null) {
                    spaceView?.visibility = View.GONE
                    this@MainActivity.toolbarLayout?.visibility = View.GONE
                } else if ((position != 1 || position != 4) && spaceView != null) {
                    spaceView?.visibility = View.VISIBLE
                    this@MainActivity.toolbarLayout?.visibility = View.VISIBLE
                }
                if (position == 0) {
                    mRightText?.visibility = View.VISIBLE

                } else {
                    mRightText?.visibility = View.GONE
                }
                if (position <= 4) {
                    //bottomBar?.selectTabAtPosition(position)
                    mTabLayout?.getTabAt(position)?.select()
                    toolbarLayout?.isTitleEnabled = position == 4 //标题固定
                    toolBar.title = resources.getString(R.string.app_name)

                    if (position == 0) {
//                        val intent = Intent(this@MainActivity, ProductImgsActivity::class.java)
//                        startActivityForResult(intent, 100)
                    } else if (position == 1) {


                    } else {
                        lastMenuIndex = position
                    }

                    KLog.d("last height : ${fl_head_container?.measuredHeight}")
                }
            }


            override fun onPageScrollStateChanged(state: Int) {}
        })
        mViewPager?.currentItem = 0
/*        bottomBar!!.setOnTabSelectListener { tabId ->
            KLog.d(bottomBar!!.currentTabPosition)
            val index = bottomBar!!.findPositionForTabWithId(tabId)
            mViewPager!!.currentItem = index
            bottomBar!!.setBadgesHideWhenActive(false)
        }

        bottomBar!!.setOnTabReselectListener { }*/
        mTabLayout?.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {
                //    onTabItemSelected(tab.position)
                this@MainActivity.mViewPager?.currentItem = tab.position
                for (i in 0 until (mTabLayout?.getTabCount() ?: 0)) {
                    val view = mTabLayout?.getTabAt(i)?.customView
                    val icon = view!!.findViewById<View>(R.id.tab_content_image) as ImageView
                    val text = view.findViewById<View>(R.id.tab_content_text) as TextView
                    if (i == tab.position) {
                        icon.setImageResource(mTabResPressed[i])
                        text.setTextColor(Color.parseColor("#0093FF"))
                    } else {
                        icon.setImageResource(mTabRes[i])
                        text.setTextColor(resources.getColor(android.R.color.darker_gray))
                    }
                }


            }

            override fun onTabUnselected(tab: TabLayout.Tab) {

            }

            override fun onTabReselected(tab: TabLayout.Tab) {

            }
        })

        for (i in 0..4) {
            mTabLayout?.addTab(mTabLayout?.newTab()?.setCustomView(getTabView(this@MainActivity, i))
                    ?: mTabLayout!!.newTab())
        }
    }

    private fun onTabItemSelected(position: Int) {

    }

    /**
     * 菜单预处理，tabLayout切换时调用 invalidateOptionsMenu();

     * @param menu
     * *
     * @return
     */
    override fun onPrepareOptionsMenu(menu: Menu): Boolean {
        currentMenu = menu
        return super.onPrepareOptionsMenu(menu)
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menu.clear()
        when (mViewPager!!.currentItem) {
            0 -> menuInflater.inflate(R.menu.main_home, menu)
            1 -> {
            }
            2 -> {

            }
            3 -> {
                menuInflater.inflate(R.menu.main_contact, menu)
            }
            4 -> {

            }

            else -> {
            }
        }
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        val id = item.itemId
        when (id) {
            R.id.action_settings -> {
                //设置
                return true
            }
            R.id.action_friends -> {
                //   UIHelper.startActivity(AddressBookActivity::class.java)
                return true
            }
            /*  case R.id.action_add_friend:
                    //添加好友
                    AddFriendActivity.start(Main22Activity.this);
                    return true;*/
            R.id.action_locate -> {
                //定位
                return true
            }
            R.id.action_signed -> {
                //签到
                return true
            }

        }
        return super.onOptionsItemSelected(item)
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        KLog.d("requestCode :$requestCode ,$resultCode , $data ")
        if (requestCode == 100) mViewPager?.currentItem = lastMenuIndex

    }

    override fun onBackPressed() {
        super.onBackPressed()
        // AppManager.get().AppExit();
    }


    override fun onDestroy() {
        super.onDestroy()
        this.mSectionsPagerAdapter?.fragments?.clear()
        this.mSectionsPagerAdapter = null
    }


    override fun getLayoutId(): Int {
        return R.layout.activity_main
    }


    //region main view impl
    override fun showLoading() {

    }

    override fun dismissLoading() {

    }


    override fun showError(e: Throwable?) {

    }


    //endregion

    override fun createPresenter() = MainPresenterImpl<MainView>()

    //region  about permission
    public override fun requestPermission() {
        rxPermissions = RxPermissions.getInstance(this)
        rxPermissions?.shouldShowRequestPermissionRationale(this@MainActivity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)?.doOnNext { aBoolean ->
            if (aBoolean!!) {
                KLog.d()
            }
        }?.flatMap { rxPermissions!!.request(Manifest.permission.WRITE_EXTERNAL_STORAGE) }?.subscribe(SimpleSubscriber<Boolean>())
    }

    /**
     * 下载新版本应用
     */
    inner class downloadAsyncTask : AsyncTask<String, Int, Int>() {

        override fun onPreExecute() {
            progressDialog?.show()
        }

        @TargetApi(19)
        override fun doInBackground(vararg params: String): Int? {
            var url: URL? = null
            var connection: HttpURLConnection? = null
            try {
                url = URL(params[0])
                connection = url.openConnection() as HttpURLConnection
            } catch (e: IOException) {
                e.printStackTrace()
            }

            if (connection == null) {
                Log.e("", "connection is null")
                return null
            }
            //为指定的文件路径创建文件输出流
            try {
                FileOutputStream(File(C.Cache.FILE_NAME)).use { out ->
                    connection?.inputStream.use { instream ->

                        val fileLength = connection!!.contentLength.toLong()
                        val file_path = File(C.Cache.FILE_PATH)
                        if (!file_path.exists()) {
                            file_path.mkdir()
                        }

                        val buffer = ByteArray(1024 * 1024)
                        var len = 0
                        var readLength: Long = 0

                        do {
                            len = instream?.read(buffer) ?: 0
                            if (len != -1) {
                                out.write(buffer, 0, len)//从buffer的第0位开始读取len长度的字节到输出流
                                readLength += len.toLong()
                                val curProgress = (readLength.toFloat() / fileLength * 100).toInt()
                                publishProgress(curProgress)
                            } else {
                                break
                            }
                        } while (true)

                        out.flush()
                        return 1

                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
                isApkDone = false
            } finally {
                connection.disconnect()
            }
            return null
        }

        override fun onProgressUpdate(vararg values: Int?) {
            progressDialog?.setProgress(values.getOrNull(0) ?: 0)
        }


        override fun onPostExecute(integer: Int?) {
            progressDialog?.dismiss()//关闭进度条
            if (!isApkDone) {
                ToastUtils.toastLong(resources.getString(R.string.str_parsing_failure))
                isApkDone = true
                return
            }
            //安装应用
            installApp()
        }

        /**
         * 安装新版本应用
         */
        private fun installApp() {
            val appFile = File(C.Cache.FILE_NAME)
            if (!appFile.exists()) {
                return
            }

            // 跳转到新版本应用安装页面
            val intent = Intent(Intent.ACTION_VIEW)
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            if (Build.VERSION.SDK_INT >= 24) { //判读版本是否在7.0以上
                //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
                val apkUri = FileProvider.getUriForFile(this@MainActivity, getPackageName() + "" +
                        ".fileprovider",
                        appFile)
                //添加这一句表示对目标应用临时授权该Uri所代表的文件
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                intent.setDataAndType(apkUri, "application/vnd.android.package-archive")
            } else {
                intent.setDataAndType(Uri.fromFile(appFile), "application/vnd.android.package-archive")
            }
            startActivity(intent)
        }
    }
}

class SectionsPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {
    val fragments: ArrayList<Fragment> = arrayListOf(HomeFragment.newInstance(), ProductImgsFragment.newInstance(""),
            NowOrderFragment.newInstance(), MineOrderFragment.newInstance(), PersonalFragment.newInstance("我的"))

    override fun getItem(position: Int) = this.fragments.getOrNull(position) ?: MyFragment()
    override fun getCount(): Int = this.fragments.size

}






